package com.jovision.sovplay;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.base.BaseActivity;
import com.aviccxzx.smarthome.entity.FeedBack;
import com.aviccxzx.smarthome.netutil.app.App;
import com.aviccxzx.smarthome.netutil.msg.MsgCenter;
import com.aviccxzx.smarthome.picker.TimePicker;
import com.aviccxzx.smarthome.service.RetrofitHelper;
import com.aviccxzx.smarthome.service.RetrofitService;
import com.aviccxzx.smarthome.utils.ChangeNameDialogUtil;
import com.aviccxzx.smarthome.utils.DialogUtil;
import com.aviccxzx.smarthome.video.CloudUtil;
import com.jovision.AppConsts;
import com.jovision.CommonUtil;
import com.jovision.JVNetConst;

import java.text.DecimalFormat;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.widget.Toast.LENGTH_SHORT;
import static android.widget.Toast.makeText;
import static com.aviccxzx.smarthome.R.id.alarm_push_checkbox;
import static com.aviccxzx.smarthome.R.id.detection_checkbox;
import static com.aviccxzx.smarthome.R.id.new_pwd;

/**
 * Created by juyang on 17/6/19.
 */

public class JVSovCameraSetActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {

    private static final String TAG = "JVSovCameraSetActivity";
    private boolean setStateOnly;//仅仅设置显示状态,防止获取到状态后重复设置一遍的问题，客户开发时更换实现方式应该不存在这个问题


    //intent 参数
    private int window;

    //1.报警设置
    private RelativeLayout alarmSetBtn;
    private LinearLayout alarmSetContentLayout;

    private TextView alarmTimeStartET;//安全防护开始时间
    private TextView alarmTimeEndET;//安全防护结束时间
    private TextView alarmSensitivityET;//安全防护结束时间
    private TextView move_set;//保存时间
    private TextView save_time;//保存时间
    private ImageView alarm_set_arrow;//报警设置箭头

    private CheckBox alarmPushBtn;//报警推送开关
    private CheckBox alarmDetectionBtn;//移动侦测开关
    private CheckBox alarmSoundBtn;//报警声音开关

    private AlertDialog alertDialog;
    private LinearLayout movelayout;

    //2.时间时区
    private int bSntp = -1;
    private int timeFormatIndex;
    private int timeZoneIndex;
    private Button timeSetBtn;
    private LinearLayout timeSetContentLayout;

    private CheckBox nbspBtn;//报警推送开关
    private Spinner spTimeZone;//时区spinner
    private Spinner spTimeFormat;//时间显示格式spinner
    private TextView mobileTimeET;//手机时间

    //3.系统设置
    private RelativeLayout systemSetBtn;
    private LinearLayout systemSetContentLayout;
    private TextView newPwdET;
    private ImageView system_set_arrow;
    //4.存储设置
    private boolean supportChFrame;//是否支持抽帧录像

    private int chFrameTime = 0;
    private int chFrameIndex = 0;//抽帧间隔list 的 index
    private int recordModeSelectIndex = 0;//录像模式index
    private int storageState;
    private RelativeLayout storageSetBtn;

    private LinearLayout storageSetContentLayout;
    private ImageView storage_set_arrow;
    private TextView storageListTV;

    private TextView storageStateTV;
    private TextView storageSituationTV;
    private Spinner spRecordMode;//录像模式spinner
    private Spinner alarm_sensitivity_spinner;//灵敏度spinner
    private Spinner spChFrameMode;//抽帧间隔spinner
    private RelativeLayout chFrameLayout;//抽帧间隔设置
    String newpwd;
    //5.版本信息
    private boolean cancelUpdate = false;

    private ImageView version_set_arrow;
    private boolean downloadSuccess = false;//下载成功
    private boolean writeSuccess = false;//烧写成功
    private int fullWritePro = 0;
    private RelativeLayout versionSetBtn;
    private LinearLayout versionSetContentLayout;
    private TextView modelTV;
    private TextView versionTV;
    private TextView downloadProTV;


    //6.其他设置
    private int effectFlag = 0;
    private Button otherSetBtn;
    private LinearLayout otherSetContentLayout;
    private CheckBox directionBtn;//设备倒装开关
    private RelativeLayout change_videopwd;//修改设备密码
    private String vpwd;//摄像机原密码
    private Boolean devAdmin;//摄像机管理员
    /**
     * 存储器
     */
    public SharedPreferences spf;
    /**
     * 存储器默认名称
     */
    public static final String SPF_Name = "set";

    @Override
    protected void initSettings() {
        window = getIntent().getIntExtra("window", 0);
        vpwd = getIntent().getStringExtra("vpwd");
        devAdmin = getIntent().getBooleanExtra("devAdmin",false);
    }

    @Override
    protected void initUi() {
        setContentView(R.layout.activity_cloud_device_set);

        spf = getSharedPreferences(SPF_Name, Context.MODE_PRIVATE);

        //1.报警设置
        alarmSetBtn = (RelativeLayout) findViewById(R.id.alarm_set);
        alarmSetContentLayout = (LinearLayout) findViewById(R.id.alarm_set_content);
        alarmSetBtn.setOnClickListener(this);

        alarmTimeStartET = (TextView) findViewById(R.id.alarm_time_start);
        alarmTimeEndET = (TextView) findViewById(R.id.alarm_time_end);
        alarmSensitivityET = (TextView) findViewById(R.id.alarm_sensitivity);

        save_time = (TextView) findViewById(R.id.save_time);
        move_set = (TextView) findViewById(R.id.move_set);
        alarm_set_arrow = (ImageView) findViewById(R.id.alarm_set_arrow);

        alarmPushBtn = (CheckBox) findViewById(alarm_push_checkbox);
        alarmDetectionBtn = (CheckBox) findViewById(detection_checkbox);
        alarmSoundBtn = (CheckBox) findViewById(R.id.alarm_sound_checkbox);
        alarmPushBtn.setOnCheckedChangeListener(mOnCheckedChangeListener);
        alarmDetectionBtn.setOnCheckedChangeListener(mOnCheckedChangeListener);
        alarmSoundBtn.setOnCheckedChangeListener(mOnCheckedChangeListener);

        //2.时间时区
        timeSetBtn = (Button) findViewById(R.id.time_set);
        timeSetContentLayout = (LinearLayout) findViewById(R.id.time_set_content);
        timeSetBtn.setOnClickListener(this);

        nbspBtn = (CheckBox) findViewById(R.id.bnsp_checkbox);
        spTimeZone = (Spinner) findViewById(R.id.src_zone_spinner);
        spTimeFormat = (Spinner) findViewById(R.id.src_type_spinner);
        mobileTimeET = (TextView) findViewById(R.id.mobile_time);
        nbspBtn.setOnCheckedChangeListener(mOnCheckedChangeListener);
        spTimeZone.setOnItemSelectedListener(this);
        spTimeFormat.setOnItemSelectedListener(this);
        mobileTimeET.setText(CommonUtil.getCurrentTime());

        //3.系统设置
        systemSetBtn = (RelativeLayout) findViewById(R.id.system_set);
        systemSetContentLayout = (LinearLayout) findViewById(R.id.system_set_content);
        systemSetBtn.setOnClickListener(this);
        newPwdET = (TextView) findViewById(new_pwd);
        system_set_arrow = (ImageView) findViewById(R.id.system_set_arrow);

        //4.存储管理
        storage_set_arrow = (ImageView) findViewById(R.id.storage_set_arrow);
        storageSetBtn = (RelativeLayout) findViewById(R.id.storage_set);
        storageSetContentLayout = (LinearLayout) findViewById(R.id.storage_set_content);
        storageSetBtn.setOnClickListener(this);
        storageListTV = (TextView) findViewById(R.id.device_list);
        storageStateTV = (TextView) findViewById(R.id.device_state);
        storageSituationTV = (TextView) findViewById(R.id.device_situation);
        spRecordMode = (Spinner) findViewById(R.id.storage_recordmode_spinner);
        alarm_sensitivity_spinner = (Spinner) findViewById(R.id.alarm_sensitivity_spinner);
        spChFrameMode = (Spinner) findViewById(R.id.storage_chframe_spinner);//抽帧间隔spinner
        spRecordMode.setOnItemSelectedListener(this);
        alarm_sensitivity_spinner.setOnItemSelectedListener(this);
        spChFrameMode.setOnItemSelectedListener(this);
        chFrameLayout = (RelativeLayout) findViewById(R.id.chframe_layout);

        //5.版本信息
        version_set_arrow = (ImageView) findViewById(R.id.version_set_arrow);
        versionSetBtn = (RelativeLayout) findViewById(R.id.version_set);
        versionSetContentLayout = (LinearLayout) findViewById(R.id.version_set_content);
        versionSetBtn.setOnClickListener(this);
        modelTV = (TextView) findViewById(R.id.model);
        versionTV = (TextView) findViewById(R.id.version);
        downloadProTV = (TextView) findViewById(R.id.download_process);

        //6.其他设置
        otherSetBtn = (Button) findViewById(R.id.other_set);
        otherSetContentLayout = (LinearLayout) findViewById(R.id.other_set_content);
        otherSetBtn.setOnClickListener(this);

        directionBtn = (CheckBox) findViewById(R.id.direction_checkbox);
        directionBtn.setOnCheckedChangeListener(mOnCheckedChangeListener);

        change_videopwd = (RelativeLayout) findViewById(R.id.change_videopwd);

        TextView cam_version = (TextView) findViewById(R.id.cam_version);

        //获取所有配置信息
        SovUtil.getStreamCatDataAll(window);

        ((TextView) findViewById(R.id.title_tv)).setText("摄像机设置");
        findViewById(R.id.ll_title_left_view).setOnClickListener(this);
        findViewById(R.id.ll_title_left_view).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        alarmTimeStartET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePicker start = new TimePicker(JVSovCameraSetActivity.this, TimePicker.HOUR_24);
                start.setGravity(Gravity.CENTER);//弹框居中
                start.setRangeStart(0, 0);//09:00
                start.setRangeEnd(23, 0);//18:30
                start.setTopLineVisible(false);
                start.setOnTimePickListener(new TimePicker.OnTimePickListener() {
                    @Override
                    public void onTimePicked(String hour, String minute) {
                        alarmTimeStartET.setText(hour + ":" + minute);
                    }
                });
                start.show();
            }
        });
        alarmTimeEndET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePicker start = new TimePicker(JVSovCameraSetActivity.this, TimePicker.HOUR_24);
                start.setGravity(Gravity.CENTER);//弹框居中
                start.setRangeStart(0, 0);//09:00
                start.setRangeEnd(23, 0);//18:30
                start.setTopLineVisible(false);
                start.setOnTimePickListener(new TimePicker.OnTimePickListener() {
                    @Override
                    public void onTimePicked(String hour, String minute) {
                        alarmTimeEndET.setText(hour + ":" + minute);
                    }
                });
                start.show();
            }
        });
        newPwdET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ChangeNameDialogUtil(JVSovCameraSetActivity.this, "修改摄像机密码", new ChangeNameDialogUtil.SureInterfance() {
                    @Override
                    public void sureTodo(String name) {
                        //确定修改 处理方案
                        newPwdET.setText(name);
                    }
                }).showSelfDialog();
            }
        });
        mobileTimeET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ChangeNameDialogUtil(JVSovCameraSetActivity.this, "手动设置摄像机时间", mobileTimeET.getText().toString(), new ChangeNameDialogUtil.SureInterfance() {
                    @Override
                    public void sureTodo(String name) {
                        //确定修改 处理方案
                        mobileTimeET.setText(name);
                    }
                }).showSelfDialog();
            }
        });
        alarmSensitivityET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ChangeNameDialogUtil(JVSovCameraSetActivity.this, "设置移动侦测灵敏度", alarmSensitivityET.getText().toString(), new ChangeNameDialogUtil.SureInterfance() {
                    @Override
                    public void sureTodo(String name) {
                        //确定修改 处理方案
                        alarmSensitivityET.setText(name);
                    }
                }).showSelfDialog();
            }
        });

        //保存时间
        save_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String startTime = alarmTimeStartET.getText().toString();
                String endTime = alarmTimeEndET.getText().toString();
                SovUtil.setStreamAlarmTime(window,
                        String.format(AppConsts.FORMAT_ALARM_ALARMTIME0SE,
                                startTime + "-"
                                        + endTime));
                App.getApp().showToast("设置成功");
            }
        });
        move_set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alarmPushBtn.isChecked() && alarmDetectionBtn.isChecked()) {
                    movelayout = (LinearLayout) LayoutInflater.from(JVSovCameraSetActivity.this).inflate(R.layout.set_move_zhence, null);
                    alertDialog = new AlertDialog.Builder(JVSovCameraSetActivity.this).create();
                    LinearLayout scenelayout = (LinearLayout) movelayout.findViewById(R.id.sence_layout);
                    TextView move_high = (TextView) scenelayout.findViewById(R.id.move_high);
                    TextView move_medium = (TextView) scenelayout.findViewById(R.id.move_medium);
                    TextView move_low = (TextView) scenelayout.findViewById(R.id.move_low);
                    move_high.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            SovUtil.setStreamAlarmMDSens(window,
                                    String.format(AppConsts.FORMATTER_NMDSENSITIVITY, 2));
                            move_set.setText("高灵敏度");
                            alertDialog.dismiss();
                        }
                    });
                    move_medium.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            SovUtil.setStreamAlarmMDSens(window,
                                    String.format(AppConsts.FORMATTER_NMDSENSITIVITY, 30));
                            move_set.setText("中灵敏度");
                            alertDialog.dismiss();
                        }
                    });
                    move_low.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            SovUtil.setStreamAlarmMDSens(window,
                                    String.format(AppConsts.FORMATTER_NMDSENSITIVITY, 60));
                            move_set.setText("低灵敏度");
                            alertDialog.dismiss();
                        }
                    });

                    alertDialog.show();
                    alertDialog.setContentView(movelayout);
                    Window window = alertDialog.getWindow();
                    ViewGroup.LayoutParams layoutParams = window.getAttributes();
                    WindowManager manager = window.getWindowManager();
                    Display display = manager.getDefaultDisplay();
                    layoutParams.width = (int) (display.getWidth() * 0.5);
                    layoutParams.height = scenelayout.getLayoutParams().height;
                    window.setAttributes((WindowManager.LayoutParams) layoutParams);
                } else {
                    App.getApp().showToast("请先打开报警推送开关和移动侦测开关");
                }
            }
        });
        change_videopwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!devAdmin){
                    App.getApp().showToast("非管理员不能修改密码！");
                    return;
                }
                LinearLayout movehelp = (LinearLayout) LayoutInflater.from(JVSovCameraSetActivity.this).inflate(R.layout.change_videopwd, null);
                final AlertDialog dialog = new AlertDialog.Builder(JVSovCameraSetActivity.this).create();
                LinearLayout changell = (LinearLayout) movehelp.findViewById(R.id.change_videopwd_ll);
                Button btn_cancle = (Button) changell.findViewById(R.id.btn_cancle);
                Button btn_sure = (Button) changell.findViewById(R.id.btn_sure);
                final EditText old_pwd = (EditText) changell.findViewById(R.id.old_pwd);
                final EditText new_pwd = (EditText) changell.findViewById(R.id.new_pwd);
                final EditText two_new_pwd = (EditText) changell.findViewById(R.id.two_new_pwd);
                btn_cancle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                btn_sure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String oldpwd = old_pwd.getText().toString().trim();
                        newpwd = new_pwd.getText().toString().trim();
                        String twonewpwd = two_new_pwd.getText().toString().trim();
                        if (TextUtils.isEmpty(oldpwd)) {
                            Toast.makeText(JVSovCameraSetActivity.this, "请输入摄像机原密码", Toast.LENGTH_LONG).show();
                            return;
                        }
                        if (!newpwd.equals(twonewpwd)) {
                            Toast.makeText(JVSovCameraSetActivity.this, "两次新密码输入不一致", Toast.LENGTH_LONG).show();
                            return;
                        }
                        if (TextUtils.isEmpty(newpwd)) {
                            Toast.makeText(JVSovCameraSetActivity.this, "请输入摄像机新密码", Toast.LENGTH_LONG).show();
                            return;
                        }
                        if (!oldpwd.equals(vpwd)) {
                            Toast.makeText(JVSovCameraSetActivity.this, "原密码输入有误，请重新输入", Toast.LENGTH_LONG).show();
                            return;
                        } else {
                            SovUtil.modifyStreamUserInfo(window, "admin", newpwd);
                            dialog.dismiss();
                        }
                    }
                });
                dialog.show();
                dialog.setContentView(movehelp);
                dialog.getWindow().clearFlags(
                        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
                dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
                Window window = dialog.getWindow();
                ViewGroup.LayoutParams layoutParams = window.getAttributes();
                WindowManager manager = window.getWindowManager();
                Display display = manager.getDefaultDisplay();
                layoutParams.width = (int) (display.getWidth() * 0.7);
                layoutParams.height = changell.getLayoutParams().height;
                window.setAttributes((WindowManager.LayoutParams) layoutParams);
            }
        });
        alarmDetectionBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alarmPushBtn.isChecked()) {
                    SovUtil.setStreamAlarmMdetectSwicth(window,
                            String.format(AppConsts.FORMATTER_SET_MDENABLE_STATE, alarmPushBtn.isChecked() ? 1 : 0));
                } else {
                    alarmDetectionBtn.setChecked(false);
                    App.getApp().showToast("请先打开报警推送开关");
                }
            }
        });
        findViewById(R.id.move_help).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //移动侦测解释
                String content = "移动侦测打开后能够监测到摄像机前面移动的人或物";
                showHelp(content);
            }
        });
        findViewById(R.id.format_help).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //移动侦测解释
                String content = "格式化SD卡会删除摄像机SD卡里的所有内容";
                showHelp(content);
            }
        });

        int version = getIntent().getIntExtra("version",0);
        if (version == 0){
            //低版本 不显示视频
            cam_version.setText("SH-SX1-001");
        }else {
            //高版本 显示视频
            cam_version.setText("SH-SX1-002");
        }
    }

    public void showHelp(String content) {
        LinearLayout movehelp = (LinearLayout) LayoutInflater.from(JVSovCameraSetActivity.this).inflate(R.layout.show_helpinfo, null);
        final AlertDialog dialog = new AlertDialog.Builder(JVSovCameraSetActivity.this).create();
        LinearLayout helpll = (LinearLayout) movehelp.findViewById(R.id.movehelp_ll);
        TextView show = (TextView) helpll.findViewById(R.id.show_content);
        show.setText(content);
        helpll.findViewById(R.id.move_help_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();
        dialog.setContentView(movehelp);
        Window window = dialog.getWindow();
        ViewGroup.LayoutParams layoutParams = window.getAttributes();
        WindowManager manager = window.getWindowManager();
        Display display = manager.getDefaultDisplay();
        layoutParams.width = (int) (display.getWidth() * 0.7);
        layoutParams.height = helpll.getLayoutParams().height;
        window.setAttributes((WindowManager.LayoutParams) layoutParams);
    }

    @Override
    public void onNotify(int what, int arg1, int arg2, Object obj) {
        handler.sendMessage(handler.obtainMessage(what, arg1, arg2, obj));
    }

    boolean nettime_switch = false;

    @Override
    public void onHandler(int what, int arg1, int arg2, Object obj) {

        switch (what) {
            //连接结果,视频异常断开时关闭此界面
            case JVNetConst.CALL_CATEYE_CONNECTED: {
                if (arg2 != JVNetConst.CCONNECTTYPE_CONNOK) {
                    this.finish();
                }
                break;
            }
            //设置协议回调
            case JVNetConst.CALL_CATEYE_SENDDATA: {
                try {
                    JSONObject root = JSON.parseObject(obj.toString());
                    int nCmd = root.getInteger(AppConsts.TAG_NCMD);
                    int nPacketType = root.getInteger(AppConsts.TAG_NPACKETTYPE);
                    int result = root.getInteger(AppConsts.TAG_RESULT);
                    String reason = root.getString(AppConsts.TAG_REASON);
                    String data = root.getString(AppConsts.TAG_DATA);
                    JSONObject dataJson = JSON.parseObject(data);
                    if (result == 0) {
                        makeText(this, "设置协议回调，错误码：" + reason, Toast.LENGTH_LONG).show();
                        return;
                    }
                    Log.e(TAG, "nPacketType=" + nPacketType + "；nCmd=" + nCmd + "；obj=" + obj.toString());
                    switch (nCmd) {
                        //配置信息全的回调
                        case JVNetConst.SRC_PARAM_ALL: {
                            refreshSetUi(dataJson);
                            break;
                        }
                        //1.报警设置相关回调
                        case JVNetConst.SRC_INTELLIGENCE: {

                            switch (nPacketType) {
                                case JVNetConst.SRC_EX_INTELLIGENCE_REFRESH://报警设置模块全部参数
                                    break;
                                case JVNetConst.SRC_EX_INTELLIGENCE_ALARM_ENABLE://报警开关
                                    if (result == 1) {
                                        makeText(JVSovCameraSetActivity.this, "设置成功", Toast.LENGTH_LONG).show();
                                    } else {
                                        makeText(JVSovCameraSetActivity.this, "设置失败", Toast.LENGTH_LONG).show();
                                    }
                                    break;
                                case JVNetConst.SRC_EX_INTELLIGENCE_MDETECT_SWITCH://移动侦测开关
                                    if (result == 1) {
                                        makeText(JVSovCameraSetActivity.this, "设置成功", Toast.LENGTH_LONG).show();
                                    } else {
                                        makeText(JVSovCameraSetActivity.this, "设置失败", Toast.LENGTH_LONG).show();
                                    }
                                    break;
                                case JVNetConst.SRC_EX_INTELLIGENCE_MDETECT_SENS://移动侦测灵敏度
                                    if (result == 1) {
                                        makeText(JVSovCameraSetActivity.this, "设置成功", Toast.LENGTH_LONG).show();
                                    } else {
                                        makeText(JVSovCameraSetActivity.this, "设置失败", Toast.LENGTH_LONG).show();
                                    }
                                    break;
                                case JVNetConst.SRC_EX_INTELLIGENCE_ALARM_SOUND://报警声音开关
                                    if (result == 1) {
                                        makeText(JVSovCameraSetActivity.this, "设置成功", Toast.LENGTH_LONG).show();
                                    } else {
                                        makeText(JVSovCameraSetActivity.this, "设置失败", Toast.LENGTH_LONG).show();
                                    }
                                    break;
                                default:
                                    break;
                            }
                            break;
                        }
                        //2.时间时区
                        case JVNetConst.SRC_TIME:
                            switch (nPacketType) {
                                case JVNetConst.SRC_EX_SETTIME_SNTP://网络校对开关
                                    if (result == 1) {
                                        nettime_switch = true;
                                        makeText(JVSovCameraSetActivity.this, "设置成功", Toast.LENGTH_LONG).show();
                                    } else {
                                        nettime_switch = false;
                                        makeText(JVSovCameraSetActivity.this, "设置失败", Toast.LENGTH_LONG).show();
                                    }
                                    break;
                                case JVNetConst.SRC_EX_SETTIME_FORMAT://时间显示格式
                                    if (result == 1) {
                                        makeText(JVSovCameraSetActivity.this, "时间格式设置成功", Toast.LENGTH_LONG).show();
                                    } else {
                                        makeText(JVSovCameraSetActivity.this, "时间格式设置失败", Toast.LENGTH_LONG).show();
                                    }
                                    break;
                                case JVNetConst.SRC_EX_SETTIME_ZONE://设置时区回调
                                    if (result == 1) {
                                        makeText(JVSovCameraSetActivity.this, "时区设置成功", Toast.LENGTH_LONG).show();
                                    } else {
                                        makeText(JVSovCameraSetActivity.this, "时区设置失败", Toast.LENGTH_LONG).show();
                                    }
                                    break;
                            }
                            break;
                        //3.系统管理，重启重置回调
                        case JVNetConst.SRC_ABOUTEYE:
                            switch (nPacketType) {
                                case JVNetConst.EX_ABOUT_REBOOT:
                                    this.finish();
                                    break;
                                case JVNetConst.EX_ABOUT_FORMAT:
                                    this.finish();
                                    break;
                            }
                            break;
                        //3.系统管理，修改管理员密码
                        case JVNetConst.SRC_REMOTE_ACCOUNT:
                            switch (nPacketType) {
                                case JVNetConst.SRC_EX_REMOTE_MODIFY:
                                    if (result == 1) {
                                        //更新机智云服务器的密码
                                        if (changeCamepwd){
                                            updateCam();
                                        }
                                    } else {
                                        makeText(JVSovCameraSetActivity.this, "密码修改失败", Toast.LENGTH_LONG).show();
                                    }
                                    break;
                            }
                            break;

                        //4.存储管理回调
                        case JVNetConst.SRC_STORAGE: {
                            switch (nPacketType) {
                                case JVNetConst.EX_STORAGE_REFRESH://存储卡相关信息
                                    refreshSDCardUi(JSON.parseObject(data));
                                    break;
                                case JVNetConst.SRC_EX_STORAGE_CMD_FORMAT://格式化SD卡回调
                                    disMissDialog();
                                    if (result == 1) {
                                        makeText(JVSovCameraSetActivity.this, "格式化成功！", Toast.LENGTH_LONG).show();
                                        // 获取设备的存储状态
                                        SovUtil.getStreamSDCard(window);
                                    } else {
                                        makeText(JVSovCameraSetActivity.this, "格式化失败", Toast.LENGTH_LONG).show();
                                    }

                                    break;
                                case JVNetConst.SRC_EX_STORAGE_RECORDMODE:
                                    if (result == 1) {
                                        makeText(JVSovCameraSetActivity.this, "录像模式设置成功", Toast.LENGTH_LONG).show();
                                    } else {
                                        makeText(JVSovCameraSetActivity.this, "录像模式设置失败", Toast.LENGTH_LONG).show();
                                    }
                                    break;
                                case JVNetConst.SRC_EX_STORAGE_RECORDMODE_CHFRAME_TIME://设置抽帧录像时间
                                    if (result == 1) {
                                        makeText(JVSovCameraSetActivity.this, "抽帧间隔设置成功", Toast.LENGTH_LONG).show();
                                    } else {
                                        makeText(JVSovCameraSetActivity.this, "抽帧间隔设置失败", Toast.LENGTH_LONG).show();
                                    }
                                    break;
                            }
                            break;
                        }
                        //设备一键升级
                        case JVNetConst.SRC_FIRMUP:
                            switch (nPacketType) {
                                //0x01  请求设备升级回调
                                case JVNetConst.SRC_EX_FIRMUP_REQ: {
                                    Log.e(TAG, getLocalClassName() + "--请求设备升级回调" +
                                            "result=" + result);
                                    if (result == 1) {
                                        SovUtil.cmdStreamCatUpdateDownload(window);
                                        downloadProTV.setVisibility(View.VISIBLE);
                                    } else {
                                        AlertDialog.Builder updateDialog = new AlertDialog.Builder(this);
                                        updateDialog.setTitle("设备升级").setMessage(reason)
                                                .setPositiveButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        dialog.dismiss();
                                                    }
                                                }).create().show();
                                    }
                                    break;
                                }
                                //0x02 收到设备开始下载升级文件回调
                                case JVNetConst.SRC_EX_UPLOAD_START_STREAM: {
                                    Log.e(TAG, getLocalClassName() + "--收到设备开始下载升级文件回调" +
                                            "result=" + result);
                                    if (result == 1) {
                                        downloadSuccess = false;
                                        SovUtil.cmdStreamCatUpdateProgress(window);
                                        int param = root.getInteger("nParam");
                                        downloadProTV.setText("下载进度：" + param + "%");
                                    } else {
                                        makeText(JVSovCameraSetActivity.this,
                                                "获取升级进度失败，reason：" + reason, LENGTH_SHORT).show();
                                    }
                                    break;
                                }
                                //0x03 取消下载升级
                                case JVNetConst.SRC_EX_UPLOAD_CANCEL_STREAM: {
                                    makeText(JVSovCameraSetActivity.this,
                                            "取消升级成功！", LENGTH_SHORT).show();
                                    break;
                                }
                                //0x04 获取下载进度
                                case JVNetConst.SRC_EX_UPLOAD_PROGRESS: {
                                    if (downloadSuccess) {
                                        return;
                                    }
                                    int param = root.getInteger("nParam");
                                    Log.e(TAG, getLocalClassName() + "--获取升级进度 " + param);
                                    if (param >= 100) {
                                        downloadProTV.setText("下载完成，发送烧写命令：" + param + "%");
                                        SovUtil.cmdStreamCatUpdateFirmUp(window);
                                        break;
                                    } else {
                                        Thread.sleep(1000);
                                        //每隔1s去获取下载进度
                                        SovUtil.cmdStreamCatUpdateProgress(window);
                                        downloadProTV.setText("下载进度：" + param + "%");
                                    }
                                    break;
                                }
                                //0x05 发送请求烧写命令回调
                                case JVNetConst.SRC_EX_FIRMUP_OK: {
                                    int param = root.getInteger("nParam");
                                    Log.e(TAG, getLocalClassName() + "--烧写 param=" + param);

                                    if (result == 1) {//开始烧写，升级过程结束
                                        downloadProTV.setText("下载完成，烧写命令发送成功：" + param + "%");
                                        SovUtil.cmdStreamCatUpdateFirmUpStart(window);
                                    } else {//烧写过程错误
                                        downloadProTV.setText("烧写出错，错误码：" + param);
                                    }
                                    break;
                                }
                                //开始烧写
                                case JVNetConst.SRC_EX_FIRMUP_START: {
                                    downloadProTV.setText("开始烧写，请勿断电！result=" + result);
                                    break;
                                }
                            }
                            break;

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }

    private ProgressDialog progressDialog;

    public void showProgressDialog(String msg) {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        progressDialog = new ProgressDialog(this, ProgressDialog.THEME_DEVICE_DEFAULT_LIGHT);
        progressDialog.setMessage(msg);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(true);
        try {
            progressDialog.show();
        } catch (WindowManager.BadTokenException exception) {
            exception.printStackTrace();
        }
    }


    /**
     * 取消对话框显示
     */
    public void disMissDialog() {
        try {
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
                progressDialog = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    boolean changeCamepwd = true;
    public void updateCam() {
        showProgressDialog("加载中...");
        boolean standard = spf.getBoolean("standard",false);
        int configure;
        if(standard){
            configure = 0;
        }else {
            configure = 1;
        }
        String yst = getIntent().getStringExtra("yst");
        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        Call<FeedBack> call = service.changeCaminfo(yst, "admin", newpwd,"","","","",configure+"");
        call.enqueue(new Callback<FeedBack>() {
            @Override
            public void onResponse(Call<FeedBack> call, Response<FeedBack> response) {
                if (response != null && response.body() != null) {
                    int code = response.body().getCode();
                    if (code == 0) {
                        makeText(JVSovCameraSetActivity.this, "密码修改成功", Toast.LENGTH_LONG).show();
                        MsgCenter.fireNull("changeVideoPwd", "");
                        disMissDialog();
                    } else {
                        //万一机智云后台密码修改失败 需要把摄像机的密码回滚
                        makeText(JVSovCameraSetActivity.this, "密码修改失败", Toast.LENGTH_LONG).show();
                        SovUtil.modifyStreamUserInfo(window, "admin", vpwd);
                        changeCamepwd = false;
                        disMissDialog();
                    }
                }
            }

            @Override
            public void onFailure(Call<FeedBack> call, Throwable t) {
                disMissDialog();
            }
        });
    }

    /**
     * 根据配置信息刷新UI
     *
     * @param streamJson
     */

    public void refreshSetUi(JSONObject streamJson) {
        setStateOnly = true;
        // 1.报警时间段
        String alarmTime = streamJson.containsKey(AppConsts.TAG_ALARM_ALARMTIME0SE) ?
                streamJson.getString(AppConsts.TAG_ALARM_ALARMTIME0SE) : AppConsts.ALARM_TIME_ALL_DAY;

        alarmTime = alarmTime.equalsIgnoreCase("-") ? AppConsts.ALARM_TIME_ALL_DAY : alarmTime;

        String[] timeArray = alarmTime.split("-");
        alarmTimeStartET.setText(timeArray[0].substring(0, 5));
        alarmTimeEndET.setText(timeArray[1].substring(0, 5));

        // 1. 安全防护开关
        int safeGuardState = streamJson.containsKey(AppConsts.TAG_SET_DEV_SAFE_STATE) ?
                streamJson.getInteger(AppConsts.TAG_SET_DEV_SAFE_STATE) : -1;//报警开关
        if (safeGuardState == 1) {
            alarmPushBtn.setChecked(true);
        } else {
            alarmPushBtn.setChecked(false);
        }

        // 2. 移动侦测开关
        int bMDEnable = streamJson.containsKey(AppConsts.TAG_SET_MDENABLE_STATE) ?
                streamJson.getInteger(AppConsts.TAG_SET_MDENABLE_STATE) : -1;//移动侦测开关

        if (bMDEnable == 1) {
            alarmDetectionBtn.setChecked(true);
        } else {
            alarmDetectionBtn.setChecked(false);
        }


        // 3. 移动侦测灵敏度
        int bMDEnableSensity = streamJson.containsKey(AppConsts.TAG_NMDSENSITIVITY) ?
                streamJson.getInteger(AppConsts.TAG_NMDSENSITIVITY) : -1;//移动侦测灵敏度
        //        alarmSensitivityET.setText(bMDEnableSensity + "");
        if (bMDEnableSensity == 2) {
            move_set.setText("高灵敏度");
        } else if (bMDEnableSensity == 30) {
            move_set.setText("中灵敏度");
        } else {
            move_set.setText("低灵敏度");
        }


        // 4. 报警声音开关
        int alarmSound = streamJson.containsKey(AppConsts.TAG_SET_ALARM_SOUND) ?
                streamJson.getInteger(AppConsts.TAG_SET_ALARM_SOUND) : -1;//报警声音开关

        if (alarmSound == 1) {
            alarmSoundBtn.setChecked(true);
        } else {
            alarmSoundBtn.setChecked(false);
        }


        //5.时区
        timeZoneIndex = streamJson.getInteger(AppConsts.TIME_ZONE);
        spTimeZone.setSelection(12 - timeZoneIndex);


        //6.网络校时开关
        bSntp = streamJson.getInteger(AppConsts.TAG_BSNTP);
        if (bSntp == 1) {
            nettime_switch = true;
            nbspBtn.setChecked(true);
        } else {
            nettime_switch = false;
            nbspBtn.setChecked(false);
        }


        //7.时间类型
        timeFormatIndex = streamJson.getInteger(AppConsts.TAG_TIME_FORMATTER);
        spTimeFormat.setSelection(timeFormatIndex);


        effectFlag = streamJson.getInteger(AppConsts.TAG_NEFFECT_FLAG);

        if (AppConsts.SCREEN_OVERTURN == CloudUtil.getVideoDirection(effectFlag)) {
            directionBtn.setChecked(true);
        } else {
            directionBtn.setChecked(false);
        }


        // 产品型号
        String productType = streamJson.getString(AppConsts.TAG_PRODUCT_TYPE);

        // 产品版本号
        String version = streamJson.getString(AppConsts.TAG_VERSION);

        modelTV.setText(productType);
        versionTV.setText(version);
        setStateOnly = false;
    }

    /**
     * 设置录像信息及存储卡信息
     */
    private void refreshSDCardUi(JSONObject streamJSON) {
        setStateOnly = true;
        Log.e(TAG, "refreshSDCardUi: " + streamJSON);
        if (streamJSON == null) {
            return;
        }
        int nStatus = streamJSON.getInteger(AppConsts.TAG_NSTATUS);
        float total, used;
        switch (nStatus) {
            case 0://无卡
                makeText(JVSovCameraSetActivity.this, "设备没插卡", Toast.LENGTH_LONG).show();
                return;
            case 1://未格式化
            case 2://已满
            case 4://空闲
            case 3://使用中
                total = streamJSON.getInteger(AppConsts.TAG_NTOTALSIZE);
                used = streamJSON.getInteger(AppConsts.TAG_NUSEDSIZE);

                total = (float) (total / 1024.0);
                used = (float) (used / 1024.0);
                //10.SD使用情况
                DecimalFormat fnum2 = new DecimalFormat("##0.00");
                DecimalFormat fnum4 = new DecimalFormat("##0.00");


                storageListTV.setText(fnum2.format(total)
                        + "GB 存储卡");
                storageStateTV.setText(getResources().getStringArray(R.array.array_sdcard_state)[nStatus]);
                storageSituationTV.setText(fnum2.format(used)
                        + "GB/"
                        + fnum2.format(total) + "GB");
                break;
        }

        // 录像模式
        recordModeSelectIndex = streamJSON.containsKey(AppConsts.N_RECORD_TYPE) ?
                streamJSON.getInteger(AppConsts.N_RECORD_TYPE) : -1;
        spRecordMode.setSelection(recordModeSelectIndex);

        if (streamJSON.containsKey(AppConsts.TAG_CHFRAMESEC) &&
                streamJSON.getInteger(AppConsts.TAG_CHFRAMESEC) > -1) {//有抽帧录像时间并且不为-1
            supportChFrame = true;
            chFrameTime = streamJSON.getInteger(AppConsts.TAG_CHFRAMESEC);//抽帧录像时间

            if (chFrameTime == 4) {
                chFrameIndex = 0;
                spChFrameMode.setSelection(0);
            } else if (chFrameTime == 20) {
                chFrameIndex = 1;
                spChFrameMode.setSelection(1);
            } else if (chFrameTime == 60) {
                chFrameIndex = 2;
                spChFrameMode.setSelection(2);
            }

        } else {
            supportChFrame = false;
        }
        setStateOnly = false;
    }


    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
        switch (adapterView.getId()) {
            //时区选择并设置
            case R.id.src_zone_spinner:
                if ((12 - timeZoneIndex) == position) {//12 - timeZoneIndex是列表index
                    break;
                }
                SovUtil.setStreamZone(window,
                        String.format(AppConsts.FORMAT_TIME_ZONE, 12 - position));

                timeZoneIndex = 12 - position;
                break;

            //时间格式选择并设置
            case R.id.src_type_spinner:

                if (timeFormatIndex == position) {
                    return;
                }
                SovUtil.setStreamTimeFormat(window,
                        String.format(AppConsts.FORMAT_TIME_FORMAT, timeFormatIndex));

                timeFormatIndex = position;
                break;

            //录像模式选择并设置
            case R.id.storage_recordmode_spinner: {
                if (recordModeSelectIndex == position) {
                    break;
                }
                String sendData = "";
                if (0 == position) {
                    sendData = String.format(Locale.CHINA, AppConsts.FORMAT_STORAGETYPE, position);
                } else if (1 == position) {
                    sendData = String.format(Locale.CHINA, AppConsts.FORMAT_STORAGETYPE, position);
                } else if (2 == position) {
                    sendData = String.format(Locale.CHINA, AppConsts.FORMAT_STORAGETYPE, position);
                } else if (3 == position) {
                    sendData = String.format(Locale.CHINA, AppConsts.FORMAT_STORAGETYPE_FRAME, position, 4);
                }

                SovUtil.setStreamRecordMode(window, sendData);
                recordModeSelectIndex = position;
                break;
            }
            //抽帧间隔选择并设置
            case R.id.storage_chframe_spinner: {
                if (chFrameIndex == position) {
                    break;
                }

                //非抽帧录像模式，不能设置抽帧间隔
                if (recordModeSelectIndex != 3) {
                    makeText(this, "非抽帧录像模式，不能设置抽帧间隔", Toast.LENGTH_LONG).show();
                } else {
                    int[] chFrameArray = getResources().getIntArray(R.array.array_ch_frame);
                    chFrameTime = chFrameArray[position];
                    //缩时录像间隔可选项有4，20，60，单位是秒，请客户自行选择设置
                    SovUtil.setStreamRecordChframe(window,
                            String.format(Locale.CHINA, AppConsts.FORMAT_STORAGETYPE_FRAME, recordModeSelectIndex,
                                    chFrameTime));
                    chFrameIndex = position;
                }


                break;
            }
            default:
                break;
        }
    }

    CheckBox.OnCheckedChangeListener mOnCheckedChangeListener = new CheckBox.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
            if (setStateOnly) {
                return;
            }

            switch (compoundButton.getId()) {
                //报警推送
                case alarm_push_checkbox: {
                    SovUtil.setStreamAlarmEnable(window,
                            String.format(AppConsts.FORMATTER_SET_DEV_SAFE_STATE, checked ? 1 : 0));
                    if (!checked) {
                        SovUtil.setStreamAlarmMdetectSwicth(window,
                                String.format(AppConsts.FORMATTER_SET_MDENABLE_STATE, 0));
                        alarmDetectionBtn.setChecked(false);
                    }

                    break;
                }
                //移动侦测
                //                case detection_checkbox: {
                //                    if (alarmPushBtn.isChecked()) {
                //                        SovUtil.setStreamAlarmMdetectSwicth(window,
                //                                String.format(AppConsts.FORMATTER_SET_MDENABLE_STATE, checked ? 1 : 0));
                //                    } else {
                //                        App.getApp().showToast("请先打开报警推送开关");
                //                    }
                //                    break;
                //                }
                //报警声音
                case R.id.alarm_sound_checkbox: {
                    SovUtil.setStreamAlarmSound(window,
                            String.format(AppConsts.FORMATTER_SET_ALARM_SOUND, checked ? 1 : 0));
                    break;
                }
                //网络校时
                case R.id.bnsp_checkbox: {
                    SovUtil.setStreamSntp(window,
                            String.format(AppConsts.FORMATTER_BSNTP, checked ? 1 : 0));
                    break;
                }
                //设备倒装
                case R.id.direction_checkbox: {
                    SovUtil.streamRotateVideo(window,
                            CloudUtil.getVideoDirection(effectFlag), effectFlag);
                    //获取所有配置信息
                    SovUtil.getStreamCatDataAll(window);
                    break;
                }
            }
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //报警设置
            case R.id.alarm_set: {
                if (alarmSetContentLayout.getVisibility() == View.VISIBLE) {
                    alarmSetContentLayout.setVisibility(View.GONE);
                    alarm_set_arrow.setBackgroundResource(R.mipmap.arrow_blue_down);
                } else {
                    alarmSetContentLayout.setVisibility(View.VISIBLE);
                    alarm_set_arrow.setBackgroundResource(R.mipmap.arrow_blue_up);
                }
                break;
            }
            //时间时区
            case R.id.time_set: {
                if (timeSetContentLayout.getVisibility() == View.VISIBLE) {
                    timeSetContentLayout.setVisibility(View.GONE);
                } else {
                    timeSetContentLayout.setVisibility(View.VISIBLE);
                }
                break;
            }
            //系统设置
            case R.id.system_set: {
                if (systemSetContentLayout.getVisibility() == View.VISIBLE) {
                    systemSetContentLayout.setVisibility(View.GONE);
                    system_set_arrow.setBackgroundResource(R.mipmap.arrow_blue_down);
                } else {
                    systemSetContentLayout.setVisibility(View.VISIBLE);
                    system_set_arrow.setBackgroundResource(R.mipmap.arrow_blue_up);
                }
                break;
            }

            //存储管理
            case R.id.storage_set: {
                if (storageSetContentLayout.getVisibility() == View.VISIBLE) {
                    storageSetContentLayout.setVisibility(View.GONE);
                    storage_set_arrow.setBackgroundResource(R.mipmap.arrow_blue_down);
                } else {
                    // 获取设备的存储状态
                    SovUtil.getStreamSDCard(window);
                    storageSetContentLayout.setVisibility(View.VISIBLE);
                    storage_set_arrow.setBackgroundResource(R.mipmap.arrow_blue_up);
                }
                break;
            }

            //版本信息
            case R.id.version_set: {
                if (versionSetContentLayout.getVisibility() == View.VISIBLE) {
                    versionSetContentLayout.setVisibility(View.GONE);
                    version_set_arrow.setBackgroundResource(R.mipmap.arrow_blue_down);
                } else {
                    versionSetContentLayout.setVisibility(View.VISIBLE);
                    version_set_arrow.setBackgroundResource(R.mipmap.arrow_blue_up);
                }
                break;
            }

            //其他
            case R.id.other_set: {
                if (otherSetContentLayout.getVisibility() == View.VISIBLE) {
                    otherSetContentLayout.setVisibility(View.GONE);
                } else {
                    // 获取设备的方向
                    CloudUtil.getCurrentVideoDirection(window);
                    otherSetContentLayout.setVisibility(View.VISIBLE);
                }
                break;
            }
            default:
                break;
        }
    }


    /*****************************************
     * 报警设置
     **********************************************/

    //设置安全防护时间段ok
    public void saveAlarmTime(View view) {
        String startTime = alarmTimeStartET.getText().toString();
        String endTime = alarmTimeEndET.getText().toString();
        SovUtil.setStreamAlarmTime(window,
                String.format(AppConsts.FORMAT_ALARM_ALARMTIME0SE,
                        startTime + "-"
                                + endTime));
    }

    //设置移动侦测灵敏度ok
    public void saveSensitiveTime(View view) {
        int setSen = Integer.parseInt(alarmSensitivityET.getText().toString());
        SovUtil.setStreamAlarmMDSens(window,
                String.format(AppConsts.FORMATTER_NMDSENSITIVITY, setSen));
    }

    /*****************************************
     * 时间设置
     **********************************************/

    //设置设备时间
    public void saveTime(View view) {
        if (!nettime_switch) {
            makeText(this, "时间设置成功！", Toast.LENGTH_LONG).show();
            SovUtil.setStreamTime(window, mobileTimeET.getText().toString().replace(" ", "-"));
        } else {
            App.getApp().showToast("网络校时已经打开，手动设置时间失效");
        }
    }


    /*****************************************
     * 存储管理
     **********************************************/

    //格式化存储卡
    public void formatSDCard(View view) {

        new DialogUtil(this, true, true, "格式化会删除摄像机SD卡里的所有内容！", "取消", "确定", new DialogUtil.SureInterfance() {
            @Override
            public void sureTodo() {
                showProgressDialog("正在格式化...");
                Log.e(TAG, "recordModeSelectIndex=" + recordModeSelectIndex);
                //        if (0 != recordModeSelectIndex) {
                //            Toast.makeText(this, "格式化SD卡之前必须先停止录像才可以", Toast.LENGTH_LONG).show();
                //        } else {
                SovUtil.setStreamSDFormat(window);
                //        }
            }

            @Override
            public void cancle() {

            }
        }).showCustomDialog();
    }

    /*****************************************
     * 系统设置
     **********************************************/
    //重启设备
    public void restartDevice(View view) {
        new DialogUtil(this, true, true, "重启设备后需要重新添加该设备！", "取消重启", "确定重启", new DialogUtil.SureInterfance() {
            @Override
            public void sureTodo() {
                makeText(JVSovCameraSetActivity.this, "设备已重启，请重新添加", Toast.LENGTH_LONG).show();
                SovUtil.streamRestart(window);
                JVSovCameraSetActivity.this.finish();
            }

            @Override
            public void cancle() {

            }
        }).showCustomDialog();

    }

    //重置设备
    public void resetDevice(View view) {
        new DialogUtil(this, true, true, "恢复出厂设置后需要重新添加该设备！", "取消重置", "确定重置", new DialogUtil.SureInterfance() {
            @Override
            public void sureTodo() {
                makeText(JVSovCameraSetActivity.this, "设备已重置，请重新添加", Toast.LENGTH_LONG).show();
                SovUtil.streamReset(window);
            }

            @Override
            public void cancle() {

            }
        }).showCustomDialog();
    }

    //修改管理员密码
    public void modifyPwd(View view) {
        SovUtil.modifyStreamUserInfo(window, "admin", newPwdET
                .getText().toString());
    }


    /*****************************************
     * 版本信息
     **********************************************/

    //设备升级
    public void updateDev(View view) {
        //TODO
        App.getApp().showToast("已经是最新版本");
//                SovUtil.cmdStreamCatUpdateInfo(window);
    }

    //取消升级
    public void cancelUpdate(View view) {
        cancelUpdate = true;
        CloudUtil.sendCancelUpdateCmd(window);
    }


    @Override
    protected void saveSettings() {

    }

    @Override
    protected void freeMe() {

    }


    /**
     * 提示设备是否重启dialog
     */
    public void restartDialog() {
        AlertDialog.Builder restartBuilder = new AlertDialog.Builder(
                JVSovCameraSetActivity.this);
        restartBuilder.setTitle("提示");
        restartBuilder.setMessage("设备升级成功");
        restartBuilder.setNegativeButton(getResources().getString(R.string.cancel),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog,
                                        int which) {
                        dialog.dismiss();
                    }
                });
        restartBuilder.setPositiveButton("立即重启",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog,
                                        int which) {
                        CloudUtil.reBootDevice(window);
                        dialog.dismiss();
                    }
                });
        restartBuilder.create().show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }
}
